package com.gardenguell.salad.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.gardenguell.salad.R;
import com.gardenguell.salad.app.AppConstant;
import com.gardenguell.salad.app.HandlerCenter;
import com.gardenguell.salad.data.client.SaladClient;
import com.gardenguell.salad.data.model.BaseModel;
import com.gardenguell.salad.data.model.Box;
import com.gardenguell.salad.data.volley.OnErrorResponse;
import com.gardenguell.salad.data.volley.OnSuccessResponse;
import com.gardenguell.salad.ui.activity.ConfigActivity;
import com.gardenguell.salad.ui.adapter.BoxAdapter;
import com.gardenguell.salad.ui.adapter.DividerLineDecoration;
import com.gardenguell.salad.ui.view.MaterialDialog;
import com.gardenguell.salad.util.DisplayUtil;
import com.gardenguell.salad.util.ResUtil;
import com.gardenguell.salad.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by absurd on 16/2/10.
 */
public class MainFragment extends BaseFragment {

    private RecyclerView mBoxList;
    private BoxAdapter mBoxAdapter;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case HandlerCenter.Message.REFRESH_BOX_LIST:
                    refreshBoxList();
                    break;
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        HandlerCenter.getInstance().setHandler(HandlerCenter.Flag.MAIN_FRAGMENT, mHandler);
        mBoxList = (RecyclerView)rootView.findViewById(R.id.box_list);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getBaseActivity());
        mBoxList.setLayoutManager(layoutManager);
        // set every item's height is fixed
        mBoxList.setHasFixedSize(true);
        List<Box> data = new ArrayList<>();
        mBoxAdapter = new BoxAdapter(data);
        mBoxAdapter.setOnRecyclerViewItemClickListener(new BoxAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, BaseModel baseModel) {
                Message message = Message.obtain();
                message.what = HandlerCenter.Message.TO_BOX_ACTIVITY;
                message.obj = baseModel;
                HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.MAIN_ACTIVITY)
                        .sendMessage(message);
            }
        });
        mBoxAdapter.setOnRecyclerViewItemLongClickListener(new BoxAdapter.OnRecyclerViewItemLongClickListener(){
            @Override
            public boolean onItemLongClicked(View view, BaseModel baseModel) {
                final Box box = (Box)baseModel;
                final MaterialDialog alert = new MaterialDialog(getBaseActivity());
                alert.setMessage(ResUtil.getString(R.string.tip_delete_box))
                        .setPositiveButton(R.string.ok, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // get the module info and config the server infos successfully
                                SaladClient client = new SaladClient();
                                client.removeBox(box.getMac(), getUsername(), new OnSuccessResponse() {
                                    @Override
                                    public void onSuccessWithNoBody() {
                                        super.onSuccessWithNoBody();
                                        Toast.makeText(getBaseActivity(), "remove box successfully", Toast.LENGTH_SHORT).show();
                                        refreshBoxList();
                                    }
                                }, getBaseActivity());
                            }
                        });
                alert.setCanceledOnTouchOutside(true);
                alert.show();
                return true;
            }
        });
        mBoxList.setAdapter(mBoxAdapter);
        DividerLineDecoration dividerLine = new DividerLineDecoration();
        dividerLine.setSize(DisplayUtil.dip2px(this.getBaseActivity(),10));
        dividerLine.setColor(ResUtil.getColor(R.color.main_background));
        mBoxList.addItemDecoration(dividerLine);
        refreshBoxList();
        return rootView;
    }

    private void refreshBoxList(){
        SaladClient client = new SaladClient();
        String username = getUsername();
        if(username == null || username.isEmpty()){
            Toast.makeText(MainFragment.this.getBaseActivity(), R.string.error_wrong_token, Toast.LENGTH_SHORT).show();
            HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.BASE_ACTIVITY)
                    .sendEmptyMessage(HandlerCenter.Message.WRONG_TOKEN);
        }
        client.getBoxList(username, new OnSuccessResponse<Box>() {
            @Override
            public void onSuccessWithList(List<Box> list) {
                super.onSuccessWithList(list);
                mBoxAdapter.setData(list);
            }

            @Override
            public void onSuccessWithNoBody() {
                super.onSuccessWithNoBody();
                // 此时从服务端返回的box列表为空
                mBoxAdapter.setData(new ArrayList<Box>());
            }
        }, this);
    }
}
